<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\common\controller\Api;
use Endroid\QrCode\QrCode;
use think\Db;

/**
 * 首页接口
 */
class Course extends Api
{
    protected $noNeedLogin = ['courseEdit','courseCommentList','courseListJkjs','courseTime'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }

    /**
     * @return void
     * @throws \think\exception\DbException
     * 课程列表
     */
    public function courseList(){
        $user = $this->auth->getUser();
        $course_category_id = $this->request->post("course_category_id");
        $label_id = $this->request->post("label_id");
        $type = $this->request->post("type",0);//0够课1预约课程
        $where['id'] = ['>',0];
        $where['is_show'] = 1;
        $where['type'] = 0;
        if($course_category_id){
            $where['course_category_id'] = $course_category_id;
        }
        if($label_id){
            $where['course_label_id'] = $label_id;
        }
        if($type == 1){
            $course_ids = Db::name("user_recharge_card")->where(['user_id'=>$user->id,'surplus_sum'=>['>',0],'status'=>1,'type'=>1])->column("course_id");
            $where['id'] = ['in',$course_ids];

           /* $course_ids = Db::name("course")->where($where)->column("id");
            $where_card['course_id'] = ['in',$course_ids];

            /////////
            $card_list = Db::name("user_recharge_card")->where($where_card)->where(['user_id'=>$user->id,'surplus_sum'=>['>',0],'status'=>1])->paginate()->toArray();
            foreach ($card_list['data'] as $k=>$v){
                // var_dump($v);exit;
                if($v['type'] == 3){
                    $wraprecharge_data = Db::name("course_wraprecharge")->where(['id'=>$v['order_id']])->find();
                    $course_wrap_data = Db::name("course_wrap")->where(['id'=>$wraprecharge_data['course_wrap_id']])->find();
                    $card_list['data'][$k]['image'] =  cdnurl($course_wrap_data['image'], true);
                    $card_list['data'][$k]['name'] =  $course_wrap_data['name'];
                }else{
                    $course_data = Db::name("course")->where(['id'=>$v['course_id']])->find();
                    $card_list['data'][$k]['image'] =  cdnurl($course_data['image'], true);
                    $card_list['data'][$k]['name'] =  $course_data['name'];
                }

                $card_list['data'][$k]['teacher_name'] =  Db::name("merchant_teacher")->where(['id'=>$v['merchant_teacher_id']])->value("name");
                $card_list['data'][$k]['card_id'] = $v['id'];

            }
            $this->success('课程列表', $card_list);*/
            ///
        }
        $list = Db::name("course")->where($where)->order("weigh desc")->paginate(100)->toArray();

        // $list = $list->toArray();
        // var_dump($list);exit;
        //  var_dump($list['data']);
        foreach ($list['data'] as $k=>$v){
            // var_dump($v);exit;
            $list['data'][$k]['image'] =  cdnurl($v['image'], true);
            $list['data'][$k]['teacher_name'] =  Db::name("merchant_teacher")->where(['id'=>$v['merchant_teacher_id']])->value("name");
            if($type == 1){
                $card_id = Db::name("user_recharge_card")->where(['user_id'=>$user->id,'course_id'=>$v['id'],'surplus_sum'=>['>',0],'status'=>1])->value("id");
                $list['data'][$k]['card_id'] = $card_id;
            }else{
                $list['data'][$k]['card_id'] = 0;
            }
        }
        if($type == 1){
            $merchant_ids = Db::name("merchant")->where(['label_id'=>$label_id])->column("id");
            //echo Db::name("merchant")->getLastSql();
            $course_wrap_data = Db::name("course_wrap")->where(['merchant_user_id'=>['in',$merchant_ids]])->column("id");
            //echo Db::name("course_wrap")->getLastSql();
            $course_wraprecharge_data = Db::name("course_wraprecharge")->where(['course_wrap_id'=>['in',$course_wrap_data]])->column("id");
            //echo Db::name("course_wraprecharge")->getLastSql();
            $card_list = Db::name("user_recharge_card")->where(['order_id'=>['in',$course_wraprecharge_data],'user_id'=>$user->id,'surplus_sum'=>['>',0],'status'=>1,'type'=>3])->select();
            //echo Db::name("user_recharge_card")->getLastSql();
            $a_arr = [];
            $a_arr_list = [];
            foreach ($card_list as $k=>$v){
                $a_arr['card_id'] = $v['id'];
                $wraprecharge_data = Db::name("course_wraprecharge")->where(['id'=>$v['order_id']])->find();
                $course_wrap_data = Db::name("course_wrap")->where(['id'=>$wraprecharge_data['course_wrap_id']])->find();
                $a_arr['image'] =  cdnurl($course_wrap_data['image'], true);
                $a_arr['name'] =  $course_wrap_data['name'];
                $a_arr['teacher_name'] =  Db::name("merchant_teacher")->where(['id'=>$v['merchant_teacher_id']])->value("name");
                $a_arr_list[] = $a_arr;
            }

            $list['data'] = array_merge( $list['data'],$a_arr_list);
            $list['per_page'] = 100;
            $list['total'] = $list['total'] + count($card_list);
        }

        $this->success('课程列表', $list);
    }
    public function courseListJkjs(){
        $user = $this->auth->getUser();
        $where['course_label_id'] = 4;
        $list = Db::name("course")->where($where)->order("id desc")->paginate()->toArray();
        // $list = $list->toArray();
        // var_dump($list);exit;
        //  var_dump($list['data']);
        foreach ($list['data'] as $k=>$v){
            // var_dump($v);exit;
            $list['data'][$k]['image'] =  cdnurl($v['image'], true);
            $list['data'][$k]['teacher_name'] =  Db::name("merchant_teacher")->where(['id'=>$v['merchant_teacher_id']])->value("name");
        }
        $this->success('即刻健身列表', $list);
    }
    /**
     * @return void
     * @throws \think\exception\DbException
     * 课表
     */
    public function timetable(){
        $user = $this->auth->getUser();
        $merchant_id = Db::name("merchant")->where(['user_id'=>$user->id])->value('id');
        $label_id = $this->request->post("label_id");
        $day = $this->request->post("day");
        $type = $this->request->post("type",0);
        $str_time = strtotime(date('Y-m-d',strtotime($day)));
        $end_time = strtotime(date('Y-m-d 23:59:59',strtotime($day)));
        if($type ==1){
            $list = Db::name("timetable")
                ->where(['label_id'=>$label_id])
                ->whereTime('time', 'between', [$str_time, $end_time])
                ->order("c_str_time asc")->paginate(1000)->toArray();

            $course_ids = Db::name("course")->where(['course_label_id'=>$label_id])->column("id");
            $where['course_id'] = ['in',$course_ids];
            $where['label_id'] = ['<>',$label_id];
            $timetable_arr = Db::name("timetable")->where($where)->whereTime('time', 'between', [$str_time, $end_time])->select();
            $list['data'] = array_merge( $list['data'],$timetable_arr);
            $list['per_page'] = 1000;
            //$list['last_page'] = 1;
            $list['total'] = $list['total'] + count($timetable_arr);
        }else{
            $list = Db::name("timetable")
                ->where(['merchant_user_id'=>$merchant_id])
                ->whereTime('time', 'between', [$str_time, $end_time])
                ->order("c_str_time asc")->paginate()->toArray();
        }

        //echo Db::name("timetable")->getLastSql();
        // $list = $list->toArray();
        // var_dump($list);exit;
        //  var_dump($list['data']);
        $this->success('课表', $list);
    }
    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 课程详情
     */
    public function courseEdit(){
        $id = $this->request->post("id");
        $data = Db::name("course")->where(['id'=>$id])->find();
        if(!$data){
            $this->error("数据有误");
        }
        $teacher_data = Db::name("merchant_teacher")->where(['id'=>$data['merchant_teacher_id']])->find();
        $data['teacher_name'] = $teacher_data['name'];
        $data['teacher_image'] = cdnurl($teacher_data['image'],true);
        //$data = Db::name("course")->where(['id'=>$id])->find();
        $images_arr = explode(',',$data['images']);
        $images_str = '';
        foreach ($images_arr as $k=>$v){
            $images_str .= cdnurl($v,true).',';
        }
        $data['images']= explode(',',trim($images_str,','));
        $data['image']=cdnurl($data['image'],true);

        $comment_list = Db::name("course_comment")->where(['course_id'=>$data['id']])->order('id desc')->limit(5)->select();
       // var_dump($comment_list);
        foreach ($comment_list as $k=>$v){
            $user_data = Db::name("user")->where(['id'=>$v['user_id']])->find();
            $comment_list[$k]['nickname'] = $user_data['nickname'];
            $comment_list[$k]['avatar'] = cdnurl($user_data['avatar'],true);
            $comment_list[$k]['createtime'] =  date('Y-m-d',$v['createtime']);
            $images_arr1 = explode(',',$v['images']);
            $images_str1 = '';
            foreach ($images_arr1 as $k1=>$v1){
                $images_str1 .= cdnurl($v1,true).',';
            }
            $comment_list[$k]['imagesstr']=trim($images_str1,',');
            $comment_list[$k]['images']= explode(',',trim($images_str1,','));
        }
        $data['comment_count'] = count($comment_list);
        $data['comment_list'] = $comment_list;
        $this->success("课程详情",$data);
    }
    public function coursePayEdit(){
        $user = $this->auth->getUser();
        $id = $this->request->post("id");
        $data = Db::name("course")->where(['id'=>$id])->field("id,name,image,price,merchant_user_id")->find();
        if(!$data){
            $this->error("数据有误");
        }
        $data['image']=cdnurl($data['image'],true);
        $coupon_data = \app\common\model\User::userCouponUse($user->id,$data['price'],$data['merchant_user_id']);
        $data['coupon_money'] = $coupon_data['dk_money']??0;
        $data['pay_money'] = sprintf("%.2f", $data['price'] - $data['coupon_money']);
        $data['coupon_id'] = $coupon_data['ids']??0;
        $merchant_score = self::getMerchantScore($user->id,$data['merchant_user_id'])+$user->score;
        $data['course_score'] = $merchant_score??0;
        $this->success("课程支付详情",$data);
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function courseCommentList(){
        $id = $this->request->post("id");
        $comment_list = Db::name("course_comment")->where(['course_id'=>$id])->order("id desc")->paginate()->toArray();
        if($comment_list){
            foreach ($comment_list['data'] as $k=>$v){
                $user_data = Db::name("user")->where(['id'=>$v['user_id']])->find();
                $comment_list['data'][$k]['nickname'] = $user_data['nickname'];
                $comment_list['data'][$k]['avatar'] = cdnurl($user_data['avatar'],true);
                $comment_list['data'][$k]['createtime'] = date('Y-m-d',$v['createtime']);
                $images_arr1 = explode(',',$v['images']);
                $images_str1 = '';
                foreach ($images_arr1 as $k1=>$v1){
                    $images_str1 .= cdnurl($v1,true).',';
                }
                $comment_list['data'][$k]['images']= explode(',',trim($images_str1,','));
            }
        }

        $this->success("课程评论",$comment_list);
    }
    public function courseOrderScore(){
        $user = $this->auth->getUser();
        $course_id = $this->request->post("course_id");
        $coupon_id = $this->request->post("coupon_id",'0');
        //$pay_type = $this->request->post("pay_type");
        $course_data = Db::name("course")->where(['id'=>$course_id])->find();
        if(!$course_data){
            $this->error("数据有误");
        }
        $pay_money = $course_data['price'];


        $coupon_data = \app\common\model\User::userCouponUse($user->id,$pay_money,$course_data['merchant_user_id']);
        $pay_money = $pay_money - $coupon_data['dk_money'];
        $coupon_ids = $coupon_data['ids'];

        $out_trade_no = date("YmdHis") . mt_rand(100000, 999999);
        $in_data['out_trade_no'] = $out_trade_no;
        $in_data['course_id'] = $course_id;
        $in_data['pay_type'] = 2;
        $in_data['merchant_user_id'] = $course_data['merchant_user_id'];
        $in_data['user_id'] = $user->id;
        $in_data['price'] = $course_data['price'];
        $in_data['sum'] = $course_data['sum'];
        $in_data['createtime'] = time();
        $in_data['status'] = 0;
        $in_data['coupon_id'] = $coupon_ids;
        $in_data['pay_money'] = $pay_money;
        $in_data['coupon_money'] = $coupon_data['dk_money'];
        $in_data['label_name'] = Db::name("course_label")->where(['id'=>$course_data['course_label_id']])->value("name");
        if($coupon_data['dk_money'] != 0){
            $in_data['is_coupon'] = 1;
        }
        $in_status = Db::name("course_order")->insertGetId($in_data);
        $merchant_score = self::getMerchantScore($user->id,$course_data['merchant_user_id']);
        $re_data['score'] = sprintf("%.2f",$user->score);
        $re_data['fixed_score'] = sprintf("%.2f",$merchant_score);
        $re_data['sum_score'] = sprintf("%.2f",$merchant_score+$user->score);
        $re_data['out_trade_no'] = $out_trade_no;
        $re_data['createtime'] = date('Y-m-d',time());
        $re_data['pay_money'] = $pay_money;
        $re_data['coupon_id'] = $coupon_id;
        $this->success("积分支付页面",$re_data);
    }
    public function courseOrder(){
        $user = $this->auth->getUser();
        $course_id = $this->request->post("course_id");
        $coupon_id = $this->request->post("coupon_id",'0');
        $pay_type = $this->request->post("pay_type");
        $out_trade_no = $this->request->post("out_trade_no");
        if(!$course_id || !$pay_type || !$out_trade_no){
            $this->error("缺少必传参数");
        }
        $course_data = Db::name("course")->where(['id'=>$course_id])->find();
        if(!$course_data){
            $this->error("数据有误");
        }

        $pay_money = $course_data['price'];
        $coupon_data = \app\common\model\User::userCouponUse($user->id,$pay_money,$course_data['merchant_user_id']);
        $pay_money = $pay_money - $coupon_data['dk_money'];
        $coupon_ids = $coupon_data['ids'];
        if($course_data['type'] == 1){//训练营
           /* $out_trade_no = date("YmdHis") . mt_rand(100000, 999999);
            $in_data_order['out_trade_no'] = $out_trade_no;
            $in_data_order['course_id'] = $course_id;
            $in_data_order['pay_type'] = 2;
            $in_data_order['merchant_user_id'] = $course_data['merchant_user_id'];
            $in_data_order['user_id'] = $user->id;
            $in_data_order['price'] = $this->request->post("price");
            $in_data_order['sum'] = 1;
            $in_data_order['createtime'] = time();
            $in_data_order['status'] = 0;
            $in_data_order['pay_money'] = $this->request->post("price");
           // $in_data_order['label_name'] = Db::name("course_label")->where(['id'=>$course_label_id])->value("name");

            $in_status = Db::name("course_order")->insertGetId($in_data_order);*/
            $in_status = Db::name("course_order")->where(['out_trade_no'=>$out_trade_no])->value("id");

            $in_data_card['user_id'] = $user->id;
            $in_data_card['order_id'] = $in_status;
            $in_data_card['course_id'] = $course_id;
            $in_data_card['end_time'] = date('Y-m-d H:i:s',$course_data['end_time']);

            $in_data_card['sum'] = 1;
            $in_data_card['surplus_sum'] = 0;
            $in_data_card['merchant_user_id'] = $course_data['merchant_user_id'];
            $in_data_card['merchant_teacher_id'] = $course_data['merchant_teacher_id'];
            $in_data_card['createtime'] = time();
            $in_data_card['type'] = 1;
            $in_data_card['is_xly'] = 1;
            $user_recharge_card_id = Db::name("user_recharge_card")->insertGetId($in_data_card);
             $prein_data['yy_time'] = "9:00-10:00";
            $prein_data['type'] = 1;
            $prein_data['course_id'] = $course_id;
            $prein_data['course_order_id'] = $in_status;
            $prein_data['user_recharge_card_id'] = $user_recharge_card_id;
            //$prein_data['course_time_ids'] = $course_time_ids;
            $prein_data['merchant_teacher_id'] = $course_data['merchant_teacher_id'];
            $prein_data['user_id'] = $user->id;
             $prein_data['day'] = strtotime(date('Y-m-d',time()));
            $prein_data['createtime'] = time();

            Db::name("course_order_pre")->insertGetId($prein_data);
        }
        if($pay_type == 2){
            $in_status = Db::name("course_order")->where(['out_trade_no'=>$out_trade_no])->value("id");
            if(!$in_status){
                $this->error("数据有误");
            }
            $in_data['status'] = 1;
            $merchant_score = self::getMerchantScore($user->id,$course_data['merchant_user_id']);
            if($merchant_score < $pay_money){
                $sy = $pay_money - $merchant_score;
                if($user->score < $sy){
                    $this->error("积分不足");
                }
                \app\common\model\User::score(-$merchant_score, $this->auth->id, "购买".$course_data['name']."课程消耗积分",1,$course_data['merchant_user_id'],$in_status);
                \app\common\model\User::score(-$sy, $this->auth->id, "购买".$course_data['name']."课程消耗积分",0,$course_data['merchant_user_id'],$in_status);
            }else{
                \app\common\model\User::score(-$pay_money, $this->auth->id, "购买".$course_data['name']."课程消耗积分",1,$course_data['merchant_user_id'],$in_status);
            }
            $merchant_user = Db::name("merchant")->where(['id'=>$course_data['merchant_user_id']])->value("user_id");
            \app\common\model\User::score($pay_money, $merchant_user, "卖出课程");

            Db::name("course_order")->where(['id'=>$in_status])->update(['status'=>1]);
            Db::name("user_coupon")->where(['id'=>['in',$coupon_ids]])->update(['is_used'=>2]);
            Db::name("course")->where(['id'=>$course_id])->setInc("sales");
            if($course_data['type'] != 1){
                $in_data_card['user_id'] = $user->id;
                $in_data_card['order_id'] = $in_status;
                $in_data_card['course_id'] = $course_id;

                $in_data_card['sum'] = $course_data['sum'];
                $in_data_card['surplus_sum'] = $course_data['sum'];
                $in_data_card['merchant_user_id'] = $course_data['merchant_user_id'];
                $in_data_card['merchant_teacher_id'] = $course_data['merchant_teacher_id'];
                $in_data_card['createtime'] = time();
                $in_data_card['type'] = 1;
                Db::name("user_recharge_card")->insertGetId($in_data_card);
            }

            $this->success("购买成功");
        }else{
            $out_trade_no = date("YmdHis") . mt_rand(100000, 999999);
            $in_data['out_trade_no'] = $out_trade_no;
            $in_data['course_id'] = $course_id;
            $in_data['pay_type'] = $pay_type;
            $in_data['merchant_user_id'] = $course_data['merchant_user_id'];
            $in_data['user_id'] = $user->id;
            $in_data['price'] = $course_data['price'];
            $in_data['sum'] = $course_data['sum'];
            $in_data['status'] = 0;
            $in_data['createtime'] = time();
            $in_data['pay_money'] = $pay_money;
            $in_data['coupon_id'] = $coupon_id;
            $in_data['coupon_money'] = $coupon_data['dk_money'];
            $in_data['label_name'] = Db::name("course_label")->where(['id'=>$course_data['course_label_id']])->value("name");
            if($coupon_id != '0'){
                $in_data['is_coupon'] = 1;
            }
            $in_status = Db::name("course_order")->insertGetId($in_data);
            //订单号

            //回调链接
            $type = "wechat";
            $notifyurl = $this->request->root(true) . '/addons/epay/index/coursenotifyx/paytype/' . $type;
            $returnurl = $this->request->root(true) . '/addons/epay/index/remap/paytype/' . $type . '/out_trade_no/' . $out_trade_no;
            $info = get_addon_info('third');
            if (!$info || !$info['state']) {

                $this->error("请在后台安装第三方登录插件");
            }
            $response = Service::submitOrder($pay_money, $out_trade_no, $type, "订单支付", $notifyurl, $returnurl,'miniapp',$user->openid);
            $this->success($out_trade_no,$response);
        }



    }
    public static function getMerchantScore($user_id,$merchant_user_id){
        $list = Db::name("user_score_log")->where(['user_id'=>$user_id,'merchant_user_id'=>$merchant_user_id,'is_fixed'=>1])->select();
        $vlu = 0;
        if($list){
            foreach ($list as $k=>$v){
                if($v['before'] > $v['after']){
                    $vlu -= abs($v['score']);
                }else{
                    $vlu += abs($v['score']);
                }
            }
        }
        return $vlu;
    }
    public function userCourseOrderList(){
        $user = $this->auth->getUser();
        $course_status = $this->request->post("course_status",0);
        $where['user_id'] = $user->id;
        $where['type'] = ['in','1,3'];
        if($course_status == 0){
            $where['status'] = ['in','1,2'];
        }else{
            $where['status'] = 3;
        }
        $list = Db::name("user_recharge_card")->where($where)->field("id,course_id,sum,surplus_sum,createtime,status,type,order_id,is_xly,end_time")->order("id desc")->paginate()->toArray();
        foreach ($list['data'] as $k=>$v){
            if($v['type'] == 1 || $v['type'] == 2){
                $card_data = Db::name("course")->where(['id'=>$v['course_id']])->find();
                // var_dump($v);exit;
                $list['data'][$k]['image'] =  cdnurl($card_data['image'], true);
               // $list['data'][$k]['str_time'] =  date('Y-m-d H:i:s',$card_data['str_time']);
                $list['data'][$k]['end_time'] =  $v['end_time'];
                $list['data'][$k]['name'] =  $card_data['name'];
            }else{
                $wraprecharge = Db::name("course_wraprecharge")->where(['id'=>$v['order_id']])->find();
                $course_wrap = Db::name("course_wrap")->where(['id'=>$wraprecharge['course_wrap_id']])->find();
                $list['data'][$k]['image'] =  cdnurl($course_wrap['image'], true);
                $list['data'][$k]['name'] = $wraprecharge['name'];
            }

            $list['data'][$k]['createtime'] =  date("Y-m-d",$v['createtime']);
        }
        $this->success('我的课程预约列表', $list);
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 我的预约-预约记录
     */
    public function userCoursePre(){
        $card_id = $this->request->post("card_id");
        $status = $this->request->post("status");
        $where['user_recharge_card_id'] = $card_id;
        $where['type'] = ['in','1,2,3'];
        if($status !== ''){
            $where['status'] = $status;
        }

        $list = Db::name("course_order_pre")->where($where)->field("id,user_id,day,course_id,status,type,course_time_ids,user_recharge_card_id,yy_time")->order("id desc")->paginate()->toArray();
        foreach ($list['data'] as $k=>$v){

            $list['data'][$k]['day'] =  date('Y-m-d',$v['day']);
            $list['data'][$k]['time'] = Db::name("timetable")->where('id','in',$v['course_time_ids'])->value("c_time");
            $list['data'][$k]['time'] = $v['yy_time'];
            if($v['type'] == 1 || $v['type'] == 2){
                $card_data = Db::name("course")->where(['id'=>$v['course_id']])->find();
                // var_dump($v);exit;
                $list['data'][$k]['image'] =  cdnurl($card_data['image'], true);
                $list['data'][$k]['name'] =  $card_data['name'];
            }else{
                $card_d = Db::name("user_recharge_card")->where(['id'=>$v['user_recharge_card_id']])->find();
                $wraprecharge = Db::name("course_wraprecharge")->where(['id'=>$card_d['order_id']])->find();
                $course_wrap = Db::name("course_wrap")->where(['id'=>$wraprecharge['course_wrap_id']])->find();
                $list['data'][$k]['image'] =  cdnurl($course_wrap['image'], true);
                $list['data'][$k]['name'] = $wraprecharge['name'];
            }
        }
        $this->success("预约记录",$list);
    }

    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 取消预约
     */
    public function courseOrderPreRe(){
        $pre_id = $this->request->post("pre_id");
        $data = Db::name("course_order_pre")->where(['id'=>$pre_id])->find();
        if(!$data){
            $this->error("数据有误");
        }
        if($data['status'] != 0){
            $this->error("不符合取消条件");
        }
       $timetable_data = Db::name("timetable")->where(['id'=>$data['course_time_ids']])->find();
        $c_time_arr = explode('-',$timetable_data['c_time']);
        $str_time = strtotime(date('Y-m-d',$timetable_data['time']).$c_time_arr[0]);
        $pre_no_re = Db::name("config")->where(['name'=>'pre_no_re'])->value('value');
        $str_time = $str_time - $pre_no_re*60;
        if(time() > $str_time){//还有30分钟不可取消
            $this->error("不符合取消条件");
        }
        Db::name("timetable")->where(['id'=>$data['course_time_ids']])->setDec('y_sum');
        Db::name("course_order_pre")->where(['id'=>$pre_id])->update(['status'=>2]);
        if($data['type'] == 1 || $data['type'] == 3){
            Db::name("user_recharge_card")->where(['id'=>$data['user_recharge_card_id']])->setInc("surplus_sum");
        }
        $this->success("取消成功");
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 已完成预约-详情
     */
    public function userCourseComment(){
        $user = $this->auth->getUser();
        $card_id = $this->request->post("card_id");
        $is_comment = $this->request->post("is_comment",0);
        $where['user_recharge_card_id'] = $card_id;
        $where['user_id'] = $user->id;
        $where['status'] = 1;
        $where['is_comment'] = $is_comment;
        $list = Db::name("course_order_pre")->where($where)->field("id,day,course_id,merchant_teacher_id")->order("id desc")->paginate()->toArray();
        foreach ($list['data'] as $k=>$v){
            $teacher_data = Db::name("merchant_teacher")->where(['id'=>$v['merchant_teacher_id']])->find();
            $card_data = Db::name("course")->where(['id'=>$v['course_id']])->find();
            // var_dump($v);exit;
            $list['data'][$k]['image'] =  cdnurl($card_data['image'], true);
            $list['data'][$k]['name'] =  $card_data['name'];
            $list['data'][$k]['teacher_name'] =  $teacher_data['name'];
            $list['data'][$k]['day'] =  date('Y-m-d',$v['day']);
        }
        $this->success("预约记录",$list);
    }
    public function putCourseComment(){
        $user = $this->auth->getUser();
        $pre_id = $this->request->post("pre_id");
        $data = Db::name("course_order_pre")->where(['id'=>$pre_id])->find();
        $card_data = Db::name("course")->where(['id'=>$data['course_id']])->find();
        $teacher_data = Db::name("merchant_teacher")->where(['id'=>$data['merchant_teacher_id']])->find();
        // var_dump($v);exit;
        $re_data['image'] =  cdnurl($card_data['image'], true);
        $re_data['teacher_name'] =  $teacher_data['name'];
        $re_data['name'] =  $card_data['name'];
        $re_data['price'] =  $card_data['price'];
        $re_data['pre_id'] =  $pre_id;
        $re_data['sum'] =  $card_data['sum'];
        $this->success("提交评论页面",$re_data);
    }
    public function courseCommentAdd(){
        $user = $this->auth->getUser();
        $order_pre_id = $this->request->post("pre_id");
        $teacher = $this->request->post("teacher");
        $course = $this->request->post("course");
        $content = $this->request->post("content");
        $images = $this->request->post("images");
        $course_order_pre = Db::name("course_order_pre")->where(['id'=>$order_pre_id])->find();
        if(!$course_order_pre){
            $this->error("数据有误");
        }
        $in_data['pre_id'] = $order_pre_id;
        $in_data['teacher'] = $teacher;
        $in_data['course'] = $course;
        $in_data['content'] = $content;
        $in_data['images'] = $images;
        $in_data['user_id'] = $user->id;
        $in_data['merchant_teacher_id'] = $course_order_pre['merchant_teacher_id'];
        $in_data['createtime'] = time();
        $in_data['course_id'] = $course_order_pre['course_id'];
        Db::name("course_comment")->insertGetId($in_data);
        Db::name("course_order_pre")->where(['id'=>$order_pre_id])->update(['is_comment'=>1]);
        $this->success("评论成功");
    }
    public function courseCommentEdit(){
        $user = $this->auth->getUser();
        $order_pre_id = $this->request->post("pre_id");
        $data = Db::name("course_comment")->where(['pre_id'=>$order_pre_id])->find();
        $card_data = Db::name("course")->where(['id'=>$data['course_id']])->find();
        $teacher_data = Db::name("merchant_teacher")->where(['id'=>$card_data['merchant_teacher_id']])->find();
        // var_dump($v);exit;

        $data['teacher_name'] =  $teacher_data['name'];
        // var_dump($v);exit;
        $data['course_image'] =  cdnurl($card_data['image'], true);
        $data['course_name'] =  $card_data['name'];
        $data['sum'] =  $card_data['sum'];
        $data['createtime'] =  date('Y-m-d',$data['createtime']);
        $data['price'] =  $card_data['price'];
        $images_arr = explode(',',$data['images']);
        $images_str = '';
        foreach ($images_arr as $k=>$v){
            $images_str .= cdnurl($v,true).',';
        }
        $data['images']= explode(',',trim($images_str,','));
        $this->success("评论详情",$data);
    }
    public function userRechargeCardList(){
        $user = $this->auth->getUser();
        $list = Db::name("user_recharge_card")->where(['user_id'=>$user->id,'type'=>2])->field("id,card_id,end_time,course_id,sum,surplus_sum,status,recharge_id")->order("id desc")->paginate()->toArray();
        // $list = $list->toArray();
        // var_dump($list);exit;
        //  var_dump($list['data']);
        foreach ($list['data'] as $k=>$v){
            $card_data = Db::name("course")->where(['id'=>$v['course_id']])->find();
            $card = Db::name("card")->where(['id'=>$v['card_id']])->find();
            $recharge = Db::name("recharge")->where(['id'=>$v['recharge_id']])->find();
            // var_dump($v);exit;
            $list['data'][$k]['image'] =  cdnurl($card_data['image'], true);
            $list['data'][$k]['name'] =  $card_data['name'];
            $list['data'][$k]['card_text'] =  $card['name'];
            $list['data'][$k]['card_day'] =  $recharge['card_day'];
        }
        // 将数据转化为数组
        //$list = $list->toArray();
        // 返回数据
        $this->success('我的课程包列表', $list);
    }
    public function courseTime(){
        $card_id = $this->request->post("card_id");
        $course_id = $this->request->post("course_id");
        $day = $this->request->post("day");
        if(!$day){
            $this->error("缺少必传参数");
        }
        //$user = $this->auth->getUser();
        //$merchant_id = Db::name("merchant")->where(['user_id'=>$user->id])->value('id');
        $card = Db::name("user_recharge_card")
            ->where(['id'=>$card_id])
            ->find();
        $str_time = strtotime(date('Y-m-d',strtotime($day)));
        $end_time = strtotime(date('Y-m-d 23:59:59',strtotime($day)));
        if($card['type']==1 || $card['type']==2){
            $list = Db::name("timetable")
                ->field("id,c_time,time,course_name,teacher_name")
                ->where(['course_id'=>$course_id])
                ->whereTime('time', 'between', [$str_time, $end_time])
                ->order("c_str_time asc")->select();
        }else{//
            $merchant_data = Db::name("merchant")->where(['id'=>$card['merchant_user_id']])->find();
            $list = Db::name("timetable")
                ->field("id,c_time,time,course_name,teacher_name")
                ->where(['label_id'=>$merchant_data['label_id']])
                ->whereTime('time', 'between', [$str_time, $end_time])
                ->order("c_str_time asc")->select();
        }

       // echo Db::name("timetable")->getLastSql();
        foreach ($list as $k=>$v){
            $list[$k]['time'] = date('Y-m-d',$v['time']);
        }
       //$arr['course_time'] = Db::name("course_time")->field("id,yy_time as time")->order("weigh desc")->select();
       //$arr['course_time'] = $list;
      //  }
        $this->success("课时列表",$list);
    }
    public function courseRpe(){
        $user = $this->auth->getUser();
       // $type = $this->request->post("type");
       // $course_order_id = $this->request->post("course_order_id");
        $user_recharge_card_id = $this->request->post("user_recharge_card_id");
      //  $course_site_id = $this->request->post("course_site_id");
        $course_time_ids = $this->request->post("course_time_ids");
        $pre_day = $this->request->post("date");
        if(!$user_recharge_card_id){
            $this->error("缺少必传参数");
        }
        $recharge_card_data = Db::name("user_recharge_card")->where(['id'=>$user_recharge_card_id])->find();
        if(!$recharge_card_data){
            $this->error("数据有误");
        }
        if($recharge_card_data['type'] == 1 && $recharge_card_data['surplus_sum'] == 0){//订单
            $this->error("课程已用完");
        }if($recharge_card_data['type'] == 2 && strtotime($recharge_card_data['end_time']) < time()){//月卡
            $this->error("课程已过期");
        }
        if($recharge_card_data['surplus_sum'] == 0){//订单
            $this->error("课程已用完");
        }
        $startTime = strtotime(date('Y-m-d',strtotime($pre_day)));
        $endTime = strtotime(date('Y-m-d 23:59:59',strtotime($pre_day)));
        if($endTime < time()){
            $this->error("预约日期选择错误");
        }
        $data = Db::name("course_order_pre")->whereBetween('day', [$startTime, $endTime])->where(['user_id'=>$user->id,'status'=>0])->find();
        //echo Db::name("course_order_pre")->getLastSql();
        if($data){
           // $this->error("当天已存在预约");
        }
        $timetable_data = Db::name("timetable")->where(['id'=>$course_time_ids])->find();
        if(!$timetable_data){
            $this->error("预约时间选择错误");
        }
        if($timetable_data['y_sum'] >= $timetable_data['sum']){
            $this->error("该时间已约满");
        }
        $in_data['yy_time'] = $timetable_data['c_time'];
        $in_data['type'] = $recharge_card_data['type'];
        $in_data['course_id'] = $recharge_card_data['course_id'];
        $in_data['course_order_id'] = $recharge_card_data['order_id'];
        $in_data['user_recharge_card_id'] = $user_recharge_card_id;
        $in_data['course_time_ids'] = $course_time_ids;
        $in_data['merchant_teacher_id'] = $recharge_card_data['merchant_teacher_id'];
        $in_data['user_id'] = $recharge_card_data['user_id'];
        $in_data['day'] = strtotime($pre_day);
        $in_data['createtime'] = time();
        if($recharge_card_data['type'] == 3){
            $in_data['merchant_teacher_id'] = $timetable_data['teacher_id'];
        }
        Db::name("course_order_pre")->insertGetId($in_data);
        if($recharge_card_data['type'] == 1 || $recharge_card_data['type'] == 3){
            Db::name("user_recharge_card")->where(['id'=>$user_recharge_card_id])->setDec("surplus_sum");
        }
        //改为进行中
        Db::name("course_order")->where(['id'=>$recharge_card_data['order_id']])->update(['status'=>2]);
        Db::name("timetable")->where(['id'=>$course_time_ids])->setInc('y_sum');
        $this->success("预约成功");
    }
    public function courseOrderList(){
        $user = $this->auth->getUser();

        $list = Db::name("course_order")
            ->where(["user_id"=>$user->id,'status'=>['>',0]])
            ->field("id,course_id,createtime,price,status,pay_type,pay_money")
            ->order("id desc")
            ->paginate()->toArray();
        foreach ($list['data'] as $k=>$v){
            $card_data = Db::name("course")->where(['id'=>$v['course_id']])->find();
            $list['data'][$k]['image'] =  cdnurl($card_data['image'], true);
            $list['data'][$k]['name'] =  $card_data['name'];
            $list['data'][$k]['createtime'] =  date('Y-m-d',$v["createtime"]);
        }
        $this->success('兑换记录课程兑换', $list);
    }
    public function courseOrderEdit(){
        $user = $this->auth->getUser();
        $order_id = $this->request->post("order_id");
        $course_data = Db::name("course_order")->field("id,course_id,createtime,price,status,pay_money,out_trade_no,pay_type")->where(['id'=>$order_id,'user_id'=>$user->id])->find();
        if(!$course_data){
            $this->error("数据有误");
        }
        $card_data = Db::name("course")->where(['id'=>$course_data['course_id']])->find();
        $course_data['image'] =  cdnurl($card_data['image'], true);
        $course_data['name'] =  $card_data['name'];
        $course_data['coupon_money'] =  sprintf("%.2f",$course_data['price'] - $course_data['pay_money']);
        $course_data['createtime'] =  date('Y-m-d',$course_data["createtime"]);
        $this->success("课程订单详情",$course_data);
    }
    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 课程申请退款
     */
    public function orderRefund(){
        $user = $this->auth->getUser();
        $order_id = $this->request->post("order_id");
        $course_data = Db::name("course_order")->where(['id'=>$order_id,'user_id'=>$user->id])->find();
        if(!$course_data){
            $this->error("数据有误");
        }
        $course_cancel = Db::name("config")->where(['name'=>"course_cancel"])->value("value");
        $s_j_t = time() - $course_data['createtime'];//实际间隔时间
        $j_j_t = $course_cancel * 3600;//设置间隔时间
        if($j_j_t > $s_j_t){
            $this->error($course_cancel."小时内不允许取消");
        }
        if($course_data['status'] > 1){
            $this->error("不符合退款条件");
        }
        $up_status = Db::name("course_order")->where(['id'=>$order_id])->update(['status'=>3]);
        if($up_status){
            //课程包改为失效
            Db::name("user_recharge_card")->where(['order_id'=>$order_id])->update(["status"=>2]);
            $this->success("申请成功");
        }else{
            $this->error("申请失败");
        }
    }
    public function orderPreoffInfo(){
        $pre_id = $this->request->post("pre_id");
        $user = $this->auth->getUser();
        $course_data = Db::name("course_order_pre")->where(['id'=>$pre_id])->field("id,course_id,status,merchant_teacher_id,type,user_recharge_card_id")->find();
        if(!$course_data){
            $this->error("数据有误");
        }
        if($course_data['status'] != 0){
            $this->error("不符合核销条件");
        }
        $card_data = Db::name("course")->where(['id'=>$course_data['course_id']])->find();
        $course_data['image'] =  cdnurl($card_data['image'], true);
        $course_data['name'] =  $card_data['name'];
        $course_data['price'] =  $card_data['price'];
        $course_data['code'] = substr(md5($course_data['id']), 0, 8);;
        $course_data['teacher_name'] =  Db::name("merchant_teacher")->where(['id'=>$course_data['merchant_teacher_id']])->value("name");

        if($course_data['type'] == 3){
            $card_d = Db::name("user_recharge_card")->where(['id'=>$course_data['user_recharge_card_id']])->find();
            $wraprecharge = Db::name("course_wraprecharge")->where(['id'=>$card_d['order_id']])->find();
            $course_wrap = Db::name("course_wrap")->where(['id'=>$wraprecharge['course_wrap_id']])->find();
            $course_data['image'] =  cdnurl($course_wrap['image'], true);
            $course_data['name'] = $wraprecharge['name'];
            $course_data['price'] = $wraprecharge['price'];
        }
        // 创建二维码
        $url = Db::name("config")->where(['name'=>'url'])->value("value");
        $text = "/pages-merchant/order/cancelAfterClass?id=".$pre_id;
        $qrCode = new QrCode($text);

// 设置图片尺寸
        $qrCode->setSize(300);

// 设置二维码颜色和背景颜色
        $qrCode->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0]);
        $qrCode->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]);

// 保存二维码到本地
        $filePath = ROOT_PATH.'/public/uploads/qrcode/'.date("Y-m-d").'/'.$pre_id.'qrcode.png';
        $filePath1 = '/uploads/qrcode/'.date("Y-m-d").'/'.$pre_id.'qrcode.png';
        $path ='/public/uploads/qrcode/'.date("Y-m-d").'/';
        if (!is_dir(ROOT_PATH.$path))
        {
            mkdir(ROOT_PATH.$path,0777,true);
        }
        $qrCode->writeFile($filePath);
        $course_data['image_url'] = $url.$filePath1;
        $this->success('课程核销详情',$course_data);
    }

    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 课程核销
     */
    public function orderPreoff(){
        $pre_id = $this->request->get("pre_id");
        $user = $this->auth->getUser();
        $course_data = Db::name("course_order_pre")->where(['id'=>$pre_id])->find();
        //echo Db::name("course_order_pre")->getLastSql();
        if(!$course_data){
            $this->error("数据有误");
        }
        if($course_data['status'] != 0){
            $this->error("不符合核销条件");
        }
        $card_data = Db::name("course")->where(['id' => $course_data['course_id']])->find();
        if($course_data['type'] ==3){
                        $card_d = Db::name("user_recharge_card")->where(['id'=>$course_data['user_recharge_card_id']])->find();
                        $wraprecharge = Db::name("course_wraprecharge")->where(['id'=>$card_d['order_id']])->find();
                        $card_data = Db::name("course_wrap")->where(['id'=>$wraprecharge['course_wrap_id']])->find();
                       $card_data['image'] =  cdnurl($card_data['image'], true);
                        $card_data['name'] = $card_data['name'];
                    }

        $merchant_id = Db::name("merchant")->where(['user_id'=>$user->id])->whereOr(['examine_user_ids_str'=>['like','%,'.$user->id.',%']])->column('id');
        if(!in_array($card_data['merchant_user_id'],$merchant_id)){
            $this->error("您没有核销权限");
        }
        $type = Db::name("user_recharge_card")->where(['id'=>$course_data['user_recharge_card_id']])->value('type');
        $hexiao_count = Db::name("course_order_pre")->where(['course_id'=>$course_data['course_id'],'status'=>1])->count();
        //第一次核销更改结束时间
        if($hexiao_count == 0 && $course_data['type'] == 2 && $type == 3){
            $recharge_data = Db::name("recharge")->where(['id'=>$course_data['order_id']])->find();
            if($recharge_data['end_time'] == 0){
                $update['end_time'] = date('Y-m-d H:i:s',strtotime("+".$recharge_data['card_day']." month", time()));
                Db::name("course_order_pre")->where(['id'=>$pre_id])->update($update);
            }

        }
        $up_status = Db::name("course_order_pre")->where(['id'=>$pre_id])->update(['status'=>1]);
        $count = Db::name("course_order_pre")->where(['user_recharge_card_id'=>$course_data['user_recharge_card_id'],'status'=>1])->count();
        $sum = Db::name("user_recharge_card")->where(['id'=>$course_data['user_recharge_card_id']])->value('sum');

        //echo $count ."==" .$sum;
        if($count == $sum){
            Db::name("user_recharge_card")->where(['id'=>$course_data['user_recharge_card_id']])->update(['status'=>3]);
        }

        if($up_status){
            $this->success("核销成功");
        }else{
            $this->error("核销失败");
        }
    }
    public function orderPreoffInfoOffedit()
    {
        $pre_id = $this->request->post("order_id");
        $user = $this->auth->getUser();
        $course_data = Db::name("course_order_pre")->where(['id' => $pre_id])->field("user_id,id,course_id,status,createtime,day,course_time_ids,type,user_recharge_card_id")->find();
        if (!$course_data) {
            $this->error("数据有误");
        }
       // $merchant_id = Db::name("merchant")->where(['user_id'=>$user->id])->value('id');

        if ($course_data['status'] != 0) {
            $this->error("不符合核销条件");
        }
        $card_data = Db::name("course")->where(['id' => $course_data['course_id']])->find();
        if($course_data['type'] ==3){
            $card_d = Db::name("user_recharge_card")->where(['id'=>$course_data['user_recharge_card_id']])->find();
            $wraprecharge = Db::name("course_wraprecharge")->where(['id'=>$card_d['order_id']])->find();
            $card_data = Db::name("course_wrap")->where(['id'=>$wraprecharge['course_wrap_id']])->find();
            $card_data['image'] =  cdnurl($card_data['image'], true);
            $card_data['name'] = $card_data['name'];
        }

        $merchant_id = Db::name("merchant")->where(['user_id'=>$user->id])->whereOr(['examine_user_ids_str'=>['like',','.$user->id.',']])->column('id');
        if(!in_array($card_data['merchant_user_id'],$merchant_id)){
       // if($card_data['merchant_user_id'] !== $merchant_id){
            $this->error("您没有核销权限");
        }
        $user_data = Db::name("user")->where(['id' => $course_data['user_id']])->find();
        $course_time_data = Db::name("timetable")->where(['id' => $course_data['course_time_ids']])->find();
        $course_data['image'] = cdnurl($card_data['image'], true);
        $course_data['name'] = $card_data['name'];
        $course_data['nickname'] = $user_data['nickname'];
        $course_data['mobile'] = $user_data['mobile'];
        $course_data['pre_time'] = date('Y-m-d',$course_data['day']).' '.$course_time_data['c_time'];
        $course_data['createtime'] = date('Y-m-d H:i:s',$course_data['createtime']);
        $this->success("核销详情",$course_data);
    }
}
